package cn.dm.example.commonUnsafe;

import cn.dm.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class StringExample1 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        long endTime = System.currentTimeMillis();
        log.info("size:{} , time:{}ms", stringBuilder.length(), (endTime - startTime));
        /**
         * 结果
         * 10:16:18.516 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4967
         *
         * 10:22:05.490 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4954 , time:19ms
         * 10:22:22.074 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4971 , time:16ms
         * 10:22:34.319 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4957 , time:14ms
         * 10:22:47.833 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4965 , time:16ms
         * 10:23:01.143 [main] INFO cn.dm.example.commonUnsafe.StringExample1 - size:4971 , time:16ms
         *
         * 每次拼接一个1,若是线程安全则应该等于预期值5000，现在小于5000说明StringBuilder是线程不安全类
         */
    }

    private static void update() {
        stringBuilder.append("1");
    }
}
